package com.rzx.dim4status.service.impl;

import com.rzx.dim4status.service.PlaceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;


@Slf4j
@Service
public class PlaceServiceImpl implements PlaceService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    //用于存储Place中的所有ID
    Set<Object> savePlaceId = new HashSet<>();

    @Override
    public Boolean addPlaceComputer() {
        float onlineSum = 0;
        float offlineSum = 0;
        Set<Object> allPlace = usePlaceId();
        if (allPlace != null) {
            for (Object o : allPlace) {//遍历Place的key
                String placeLine = (String) stringRedisTemplate.opsForHash().get("placeMessage", o);
                String[] add = placeLine.split(",");
                onlineSum = Float.parseFloat(add[1]) + onlineSum;
                offlineSum = Float.parseFloat(add[2]) + offlineSum;
            }
        }
        if (offlineSum / onlineSum >= 0.66666) {
            stringRedisTemplate.opsForValue().set("global:dim4-server-status", "stop");
            return false;
        } else {
            return true;
        }
    }

    @Override
    public Set<Object> usePlaceId() {
        savePlaceId = stringRedisTemplate.opsForHash().keys("placeMessage");
        return savePlaceId;
    }

    @Override
    public Boolean changePlaceState(String id, Integer online, Integer offline) {
        stringRedisTemplate.opsForHash().put("placeMessage", id, "," + online + "," + offline + ",");
        addPlaceComputer();
        return stringRedisTemplate.opsForHash().hasKey("placeMessage", id);
    }

    @Override
    public List<Map<String, String>> findAllPlace() {
        List<Map<String, String>> allPlace = new ArrayList<Map<String, String>>();
        Set<Object> allPlaceId = usePlaceId();
        for (Object key : allPlaceId) {
            Map<String, String> placeState = new HashMap<>();
            placeState.put("placeId", (String) key);
            String placeLine = (String) stringRedisTemplate.opsForHash().get("placeMessage", key);
            String[] state = placeLine.split(",");
            placeState.put("placeOnline", state[1]);
            placeState.put("placeOffline", state[2]);
            allPlace.add(placeState);
        }
        return allPlace;
    }

    @Override
    public Map<String, String> findPlaceStateById(String id) {
        Map<String, String> map = new HashMap<>();
        String placeLine = (String) stringRedisTemplate.opsForHash().get("placeMessage",id);
        String[] placeStateById = placeLine.split(",");
        map.put("placeId",id);
        map.put("placeOnline", placeStateById[1]);
        map.put("placeOffline", placeStateById[2]);
        return map;
    }

}

